import logging
import pymysql
from exceptions import Custom_exception
import os


class Database(object):
    def __init__(self):
        self.db = Database.__getConnect()


    @staticmethod
    def __getConnect():

        # chen：增加
        data = eval(os.environ['DATABASE_URL'])

        try:
            # 初始化一个连接对象
            db = pymysql.connect(**data,
            autocommit=True,)

            return db

        except Exception as e:
            raise Custom_exception.DatabaseError(e)

    def get_one(self, sql):
        """
        查询之后获取一条数据
        :param sql:
        :return:
        """
        with self.db.cursor(cursor=pymysql.cursors.DictCursor) as cur:
            cur.execute(sql)
            return cur.fetchone()

    def get_all(self, sql):
        """
        查询之后获取多条数据
        :param sql:
        :return:
        """
        with self.db.cursor(cursor=pymysql.cursors.DictCursor) as cur:
            cur.execute(sql)
            return cur.fetchall()

    def execute_sql(self, sql):
        """
        修改和删除数据
        :return:
        """
        with self.db.cursor(cursor=pymysql.cursors.DictCursor) as cur:
            try:
                rows = cur.execute(sql)
            except Exception as e:
                logging.warning(f"执行SQL语句报错: {e}")
            else:
                print(f"影响了{rows}行")
                self.db.commit()


    def execute_sqls(self, *sql):
        """
        修改和删除数据
        执行多条语句
        :return:
        """
        with self.db.cursor(cursor=pymysql.cursors.DictCursor) as cur:
            try:
                for i in sql:
                    rows = cur.execute(i)
            except Exception as e:
                logging.warning(f"执行SQL语句报错: {e}")
            else:
                print(f"影响了{rows}行")
                self.db.commit()



if __name__ == '__main__':
    data = Database()
    sql = 'SELECT js.current_number from jsh_material jm join jsh_material_current_stock js on jm.id = js.material_id where `name` = "小米剃须刀"'
    res = data.get_one(sql)


    print(res)
